<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="仓库编码" prop="warehouseCode">
        <el-input
          v-model="queryParams.warehouseCode"
          placeholder="请输入仓库编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库名称" prop="warehouseName">
        <el-input
          v-model="queryParams.warehouseName"
          placeholder="请输入仓库名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['warehouse:warehouse:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['warehouse:warehouse:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['warehouse:warehouse:remove']"
        >删除</el-button>
      </el-col>
      
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="warehouseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="仓库编码" align="center" prop="warehouseCode" width="200px"/>
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="位置" align="center" prop="location" />
      <el-table-column label="面积" align="center" prop="area" />
      <el-table-column label="负责人" align="center" prop="charge" />
      <el-table-column label="是否冻结" align="center" prop="enableFlag" >
        <template #default="scope">
          <el-switch 
            v-model="scope.row.enableFlag" 
            active-value="N"
            inactive-value="Y"
            active-text="是" 
            inactive-text="否"
            @change="handleEnableChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220">
        <template #default="scope">
          <el-button link type="primary" icon="Shop" @click="region(scope.row)" >库区</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['warehouse:warehouse:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['warehouse:warehouse:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageDto.current"
      v-model:limit="queryParams.pageDto.size"
      @pagination="getList"
    />

    <!-- 添加或修改仓库设置对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body  @close="resetDialogForm" >
    <!-- 表单区域 -->
      <el-form ref="warehouseRef" :model="form" :rules="rules" size="medium" label-width="100px">
        <el-row gutter="15">
          <!-- 仓库编码 + 自动生成开关（修复文字位置） -->
          <el-col :span="12">
            <el-form-item label="仓库编码" prop="warehouseCode" >
              <el-input 
                v-model="form.warehouseCode" 
                placeholder="请输入仓库编码" 
                clearable
                :disabled="autoGenerateCode"  
                :style="{width: '80%'}"
              ></el-input>
              <!-- 自动生成文字移到开关后面 -->
              <el-switch 
                v-model="autoGenerateCode" 
                style="margin-left: 10px;"
                @change="handleCodeSwitchChange" 
              ></el-switch>
          <span style="margin-left: 5px;">自动生成</span>
            </el-form-item>
          </el-col>

          <!-- 仓库名称 -->
          <el-col :span="24">
            <el-form-item label="仓库名称" prop="warehouseName">
              <el-input 
                v-model="form.warehouseName" 
                placeholder="请输入仓库名称" 
                clearable
                :style="{width: '100%'}"
              ></el-input>
            </el-form-item>
          </el-col>

          <!-- 面积 -->
          <el-col :span="12">
            <el-form-item label="面积" prop="area">
              <el-input-number 
                v-model="form.area" 
                placeholder="0" 
                :min="0" 
                :precision="2"  
                :style="{width: '100%'}"
              ></el-input-number>
            </el-form-item>
          </el-col>

          <!-- 负责人 -->
          <el-col :span="24">
            <el-form-item label="负责人" prop="charge">
            <el-input style="width: 550px;" v-model="form.charge" placeholder="请选择负责人" disabled/>
            <el-icon @click="kaii" style="border: 1px solid #DCDFE6;width: 30px;height: 30px;background-color: #F5F7FA;cursor: pointer;"><Search /></el-icon>
          </el-form-item>
          </el-col>

          <el-form-item label="位置" prop="location">
          <el-input v-model="form.location" type="textarea" placeholder="请输入内容" />
        </el-form-item>

          <!-- 备注 -->
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input 
                v-model="form.remark" 
                type="textarea" 
                placeholder="请输入备注内容"
                :autosize="{minRows: 4, maxRows: 5}" 
                :style="{width: '100%'}"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 确定/取消按钮（修复显示问题：移到el-dialog直接子元素） -->
      <div  class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
      
      </el-dialog>

      <!-- 负责人选择框 -->
     <el-dialog :title="title" v-model="open2" width="1200px" class="tankuang" append-to-body   @close="handleDialogClose">
      <el-row :gutter="20">
      <splitpanes :horizontal="appStore.device === 'mobile'" class="default-theme">
        <!--部门数据-->
        <pane size="16">
          <el-col>
            <div class="head-container">
              <el-input v-model="deptName" placeholder="请输入部门名称" clearable prefix-icon="Search" style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="deptOptions" :props="{ label: 'label', children: 'children' }" :expand-on-click-node="false" :filter-node-method="filterNode" ref="deptTreeRef" node-key="id" highlight-current default-expand-all @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>
        <!--用户数据-->
        <pane size="84">
          <el-col>
            <el-form :model="queryParams1" ref="queryRef" :inline="true" v-show="showSearch1" label-width="68px">
              <el-form-item label="用户名称" prop="userName">
                <el-input v-model="queryParams1.userName" placeholder="请输入用户名称" clearable style="width: 240px" @keyup.enter="handleQuery1" />
              </el-form-item>
              <el-form-item label="手机号码" prop="phonenumber">
                <el-input v-model="queryParams1.phonenumber" placeholder="请输入手机号码" clearable style="width: 240px" @keyup.enter="handleQuery1" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery1">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery1">重置</el-button>
              </el-form-item>
            </el-form>

            <el-table v-loading="loading1"   ref="userTableRef" :data="userList1" @selection-change="handleRadioChange">
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column label="用户名称" align="center" key="userName" prop="userName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
              <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" v-if="columns[2].visible" :show-overflow-tooltip="true" />
              <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName" v-if="columns[3].visible" :show-overflow-tooltip="true" />
              <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" v-if="columns[4].visible" width="120" />
             
              <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[6].visible" width="160">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
              
            </el-table>
            <pagination v-show="total1 > 0" :total="total1" v-model:page="queryParams1.pageNum" v-model:limit="queryParams1.pageSize" @pagination="getList1" />
          </el-col>
        </pane>
      </splitpanes>
       <el-button style="margin-left: 950px;" type="primary" @click="confirmSelectedItem">确 认</el-button>
          <el-button @click="cancel1">关 闭</el-button>
    </el-row>
     </el-dialog>
  </div>
</template>

<script setup name="Warehouse">
import { listWarehouse, getWarehouse, delWarehouse, addWarehouse, updateWarehouse } from "@/api/warehouse/warehouse"

const { proxy } = getCurrentInstance();
// 新增：自动生成编码开关状态
const autoGenerateCode = ref(false)
const warehouseList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const open2 = ref(false)
import { useRouter } from 'vue-router'//进行路由跳转
const router=useRouter()
// 存储当前选中的用户
const selectedUser = ref(null);

//仓库负责人
 function kaii() {
   // open.value=false
    open2.value=true
}
import useAppStore from '@/store/modules/app'
import {  listUser,deptTreeSelect } from "@/api/system/user";
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"


const appStore = useAppStore()

const userList1 = ref([]);

const loading1 = ref(true);
const showSearch1 = ref(true);
const total1 = ref(0);
const ids1 = ref([])
const dateRange = ref([]);
const deptName = ref("");
const deptOptions = ref(undefined);
const enabledDeptOptions = ref(undefined);


// 列显隐信息
const columns = ref([
  { key: 0, label: `用户编号`, visible: true },
  { key: 1, label: `用户名称`, visible: true },
  { key: 2, label: `用户昵称`, visible: true },
  { key: 3, label: `部门`, visible: true },
  { key: 4, label: `手机号码`, visible: true },
  { key: 5, label: `状态`, visible: true },
  { key: 6, label: `创建时间`, visible: true }
]);

const data1 = reactive({
  form1: {},
  queryParams1: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    phonenumber: undefined,
    status: undefined,
    deptId: undefined
  },

});

const { queryParams1, form1 } = toRefs(data1);

/** 通过条件过滤节点  */
const filterNode = (value, data1) => {
  if (!value) return true;
  return data1.label.indexOf(value) !== -1;
};

/** 根据名称筛选部门树 */
watch(deptName, val => {
  proxy.$refs["deptTreeRef"].filter(val);
});

/** 查询用户列表 */
function getList1() {
  loading1.value = true;
  listUser(proxy.addDateRange(queryParams1.value, dateRange.value)).then(res => {
    loading1.value = false;
    userList1.value = res.rows;
    total1.value = res.total;
  });
};

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
    enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(response.data)));
  });
};

/** 过滤禁用的部门 */
function filterDisabledDept(deptList) {
  return deptList.filter(dept => {
    if (dept.disabled) {
      return false;
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children);
    }
    return true;
  });
};

/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams1.value.deptId = data.id;
  handleQuery1();
};

/** 搜索按钮操作 */
function handleQuery1() {
  queryParams1.value.pageNum = 1;
  getList1();
};

/** 重置按钮操作 */
function resetQuery1() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  queryParams1.value.deptId = undefined;
  proxy.$refs.deptTreeRef.setCurrentKey(null);
  handleQuery1();
};



/** 重置操作表单 */
function reset1() {
  form1.value = {
    userId: undefined,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    password: undefined,
    phonenumber: undefined,
    email: undefined,
    sex: undefined,
    status: "0",
    remark: undefined,
    postIds: [],
    roleIds: []
  };
  proxy.resetForm("userRef");
};

// 多选框选中数据
function handleRadioChange(selection) {
  ids1.value = selection.map(item => item.workorderId)
  single.value = selection.length != 1
  multiple.value = !selection.length
    selectedUser.value = selection.length > 0 ? selection[0] : null;

}
// 选中按钮
function confirmSelectedItem() {
  if (!selectedUser.value) {
    proxy.$modal.msgWarning("请选择一个物料");
    return;
  }
  console.log(selectedUser.value);
  
  // 将选中的物料信息回填到表单
  
  form.value.charge = selectedUser.value.nickName;
  // 关闭物料选择框，返回工单表单
  open2.value = false;
  open.value = true;

}
const userTableRef = ref(null); // 用于获取el-table实例
// 对话框关闭时的处理方法
const handleDialogClose = () => {
  open2.value = false;
  open.value = true;
  if (userTableRef.value) {
    userTableRef.value.clearSelection(); // 清空表格多选框选中状态
  }
};

function cancel1() {
  open2.value = false
  open.value = true
  if (userTableRef.value) {
    userTableRef.value.clearSelection(); // 清空表格多选框选中状态
  }
}
getDeptTree();
getList1();



const data = reactive({
  form: {},
  queryParams: {
    pageDto: {
      current: 1,
      size: 10,
    },
    warehouseCode: null,
    warehouseName: null,
  },
  rules: {
    warehouseCode: [
      { required: true, message: "仓库编码不能为空", trigger: "blur" }
    ],
    warehouseName: [
      { required: true, message: "仓库名称不能为空", trigger: "blur" }
    ],
  }
  
})
/** 生成仓库编码（规则：WS-YYYYMMDDHHmmss，如WS-20240520143025） */
function generateWorkshopCode() {
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  const second = String(date.getSeconds()).padStart(2, '0')
  const code = `CK-${year}${month}${day}${hour}${minute}${second}`
  form.value.warehouseCode = code
}

/** 自动生成开关变化事件 */
function handleCodeSwitchChange() {
  if (autoGenerateCode.value) {
    generateWorkshopCode()
  } else {
    form.value.warehouseCode = null  // 关闭时清空手动输入
    
  }
}

// 表单ref（与模板中ref="warehouseRef"对应）
const warehouseRef = ref();
// 对话框关闭时：重置表单 + 关闭开关
function resetDialogForm() {
  // 关闭“自动生成”开关
  autoGenerateCode.value = false;

  // 清除验证状态
  if (warehouseRef.value) {
    warehouseRef.value.clearValidate(); // 清除所有字段验证
  }
  // 清空表单数据
  data.form = {};
  open.value = false;
}



const { queryParams, form, rules } = toRefs(data)
import { ElMessage, ElMessageBox } from 'element-plus'



//是否启用开关
const handleEnableChange = async (row) => {
  try {
    await ElMessageBox.confirm(
      `你确认要${row.enableFlag === 'N' ? '冻结' : '启用'}‘${row.warehouseName}’仓库吗?`,
      '系统提示',
      {
        type: 'warning',
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }
    );
    // 用户确认后执行更新
    const response = await updateWarehouse(row);
    //console.log(response)
    if (response.code=200) {
      ElMessage.success("操作成功");
      getList()
    } else {
      ElMessage.error("操作失败");
      getList()
    }
  } catch (error) {
    // 捕获取消操作异常，恢复原始状态
    if (error.name === 'CanceledError'|| error.message === 'cancel' || error === 'cancel') {
      getList()
    } else {
      ElMessage.error("操作出错，请重试");
      getList()

    }
  }
}


/** 查询仓库设置列表 */
function getList() {
   loading.value = true
  listWarehouse(queryParams.value).then(response => {
    warehouseList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    warehouseId: null,
    warehouseCode: null,
    warehouseName: null,
    location: null,
    area: null,
    charge: null,
    enableFlag: 'N',
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("warehouseRef")
}

/** 搜索按钮操作 */
function handleQuery() {
 queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
   ids.value = selection.map(item => item.warehouseId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加仓库设置"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _warehouseId = row.warehouseId || ids.value
  getWarehouse(_warehouseId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改仓库设置"
  })
}

/** 提交按钮 */
function submitForm() {
   proxy.$refs["warehouseRef"].validate(valid => {
    if (valid) {
      if (form.value.warehouseId != null) {
        updateWarehouse(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addWarehouse(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
  
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _warehouseIds = row.warehouseId || ids.value
  proxy.$modal.confirm('是否确认删除仓库设置编号为"' + _warehouseIds + '"的数据项？').then(function() {
    return delWarehouse(_warehouseIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}
getList()


//跳转到库区
function region(row){
  console.log(row);
  
  router.push(`/storage/location/${row.warehouseId}`)

}
</script>
<style>
.tankuang{
  height: 600px;
}
</style>